package com.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.entity.UserAddress;
import com.mall.enums.CodeNumEntity;
import com.mall.exception.ServiceException;
import com.mall.mapper.UserAddressMapper;
import com.mall.mapper.UserMapper;
import com.mall.service.IUserAddressService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: liang
 * @time: 2024-01-17 17:07
 */
@Component
public class UserAddressServiceImpl implements IUserAddressService {

    @Resource
    private UserAddressMapper userAddressMapper;
    @Resource
    private UserMapper userMapper;

    @Override
    public int removeAddress(Integer addressId) {
        int i = userAddressMapper.deleteByAddressId(addressId);
        if(i == 0)
            throw new ServiceException(CodeNumEntity.DATABASE_ERROR.getCode(), CodeNumEntity.DATABASE_ERROR.getMessage());
        return 1;
    }

    @Override
    public UserAddress addAddress(UserAddress address) {
        if( userAddressMapper.insertSelective(address) == 0 ){
            throw new ServiceException(CodeNumEntity.DATABASE_ERROR.getCode(), CodeNumEntity.DATABASE_ERROR.getMessage());
        }

        return address;
    }

    @Override
    public List<UserAddress> queryAllUserAddressByUserId(String userId) {
        return userAddressMapper.selectUserAddressByUserId(userId);

    }

    @Override
    public UserAddress queryAddressByAddressId(int addressId) {
        return userAddressMapper.selectByPrimaryKey(addressId);
    }

    @Override
    public UserAddress modifyUserAddress(UserAddress address) {
        address.setUpdateTime(new Date());
        if (userAddressMapper.updateByPrimaryKeySelective(address) == 0) {
            throw new ServiceException(CodeNumEntity.DATABASE_ERROR.getCode(), CodeNumEntity.DATABASE_ERROR.getMessage());
        }
        return address;
    }

    /**
     * 查询用户收货地址
     * @return
     */
    @Override
    public List<UserAddress> queryUserAddress(String userId) {
        return userAddressMapper.selectList(new QueryWrapper<UserAddress>().eq("user_id",userId).eq("is_delete",0));
    }
}
